package top.lingkang.mm.solon;

import cn.hutool.core.io.IoUtil;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.noear.solon.core.BeanBuilder;
import org.noear.solon.core.BeanWrap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.lingkang.mm.error.MagicException;

/**
 * @author lingkang
 * Created by 2024/4/24
 */
public class Mapper2BeanBuilder implements BeanBuilder<Mapper> {
    private static final Logger log = LoggerFactory.getLogger(Mapper2BeanBuilder.class);
    private final SqlSessionFactory sessionFactory;

    public Mapper2BeanBuilder(SqlSessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void doBuild(Class<?> clz, BeanWrap bw, Mapper anno) throws Throwable {
        if (!clz.isInterface())
            throw new MagicException("@Mapper 只能作用在接口上，当前：" + clz.getName());
        Configuration configuration = sessionFactory.getConfiguration();
        if (!configuration.hasMapper(clz)) {
            // 注册到mapper
            configuration.addMapper(clz);
        } else
            log.debug("mapper接口已经加载: " + clz.getName());

        Object bean = bw.context().getBean(clz);
        if (bean != null) {
            return;
        }

        // 注册bean
        SqlSession session = sessionFactory.openSession();// 必须设置session，否则后期获取到空指针
        Object mapper = configuration.getMapper(clz, session);
        bw.rawSet(mapper);// 设置成 bean
        IoUtil.close(session);
        log.debug("加载 mapper 接口: " + clz.getName());
    }
}
